package com.tiantian.user.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.map.MapUtil;
import com.tiantian.common.core.constant.CacheConstants;
import com.tiantian.common.core.constant.Constants;
import com.tiantian.common.core.domain.LoginUser;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.domain.model.LoginBody;
import com.tiantian.common.redis.utils.RedisUtils;
import com.tiantian.common.satoken.utils.LoginHelper;
import com.tiantian.user.domain.entity.SysUser;
import com.tiantian.user.service.SysLoginService;
import com.tiantian.user.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录验证
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class SysLoginController {

    private final SysLoginService loginService;
    private final SysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ResponseResult.ok(ajax);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @SaIgnore
    public ResponseResult<Void> logout() {
        loginService.logout();
        return ResponseResult.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    @SaCheckLogin
    public ResponseResult<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long userId = loginUser.getUserId();
        // 尝试从缓存中获取用户信息
        Map<String, Object> userInfoForCache = RedisUtils.getCacheObject(CacheConstants.USER_INFO_KEY + userId);
        if (MapUtil.isNotEmpty(userInfoForCache)) {
            return ResponseResult.ok(userInfoForCache);
        }
        SysUser userInfo = userService.selectUserById(userId);
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("userInfo", userInfo);
        ajax.put("role", loginUser.getRoleDTO());
        ajax.put("permissions", loginUser.getPermissions());
        // 对用户信息进行缓存
        RedisUtils.setCacheObject(CacheConstants.USER_INFO_KEY + userId, ajax);
        return ResponseResult.ok(ajax);
    }

}
